'use strict'

const _ = require('lodash');
const userService = require("../services/admin/userService");
const loginLogService = require("../services/admin/loginLogService");
const opLogService = require("../services/admin/opLogService");

const helper = {};

helper.setMenus = async function (req, user_id)  {
    var menus = [], userRole = [], menu_active = {};
    var menu_roles = await userService.getMyMenus(user_id);
    if (menu_roles && menu_roles.length) {
        for (var i = 0; i < menu_roles.length; i++) {
            var menuRoleObj = menu_roles[i];
            var parent_id = menuRoleObj['parent_id'];
            if (_.indexOf(userRole, menuRoleObj['role_id']) == -1) {
                userRole.push(menuRoleObj['role_id']);
            }
            if (parent_id == 0) {
                var menuObj = {};
                menuObj['parent_id'] = parent_id;
                menuObj['menu_id'] = menuRoleObj['menu_id'];
                menuObj['menu_name'] = menuRoleObj['menu_name'];
                menuObj['menu_url'] = menuRoleObj['menu_url'];
                menuObj['menu_icon'] = menuRoleObj['menu_icon'];
                menuObj['menu_child'] = [];
                menus.push(menuObj);
                menu_active[menuRoleObj['menu_url']] = {}
            } else {
                for (var j = 0; j < menus.length; j++) {
                    var menuObj = menus[j];
                    var pid = menuObj['menu_id'];
                    if (pid == parent_id) {
                        var childObj = {}, menu_id = menuRoleObj['menu_id'], menu_url = menuRoleObj['menu_url'];
                        childObj['menu_id'] = menu_id;
                        childObj['parent_id'] = menuRoleObj['parent_id'];
                        childObj['menu_name'] = menuRoleObj['menu_name'];
                        childObj['menu_url'] = menu_url;
                        childObj['menu_icon'] = menuRoleObj['menu_icon'];
                        menuObj['menu_child'].push(childObj);
                        menu_active[menu_url] = {parent_id: parent_id, menu_id: menu_id}
                    }
                }
            }
        }
    }
    req.session.userRole = userRole;
    req.session.menus = menus;
    req.session.menu_roles = menu_roles;
    req.session.menu_active = menu_active;
};

helper.saveOpLog = async function(user_id, user_name, name, operations){
    return opLogService.saveOperateLog({
        user_id: user_id,
        user_name: user_name,
        name: name,
        operations: operations,
        operate_time: Date.now()
    });
};

helper.saveLoginLog = async function(user_id, user_name, name, client_ip){
    return loginLogService.saveLoginLog({
        user_id: user_id,
        user_name: user_name,
        name: name,
        ip: client_ip,
        login_time: Date.now()
    });
};

module.exports = helper;